package cn.autumnorange.app.gateway.zuul;

import cn.autumnorange.app.gateway.busconfig.BusConfigRequestWrapper;
import cn.autumnorange.app.gateway.util.IpUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Email miles02@163.com
 *
 * @author fangzhipeng create 2018-07-09
 */
@Slf4j
@Component
public class GateWayPreFilter extends ZuulFilter
    implements GateWayRPCIDHeaderStrategy, GateWayFilterHandle {
  //  @Autowired private OAuth2SsoProperties oAuth2SsoProperties;

  @Value("${auth-check-client-msg-uri}")
  private String authCheckClientMsgUri;

  @Value("${security.oauth2.client.client-id}")
  private String clientId;

  @Value("${security.oauth2.client.client-secret}")
  private String clientSecret;

  @Value("${server.port}")
  private int port;
  // 配置中心服务id
  @Value("${zuul.routes.config-server.serviceId}")
  private String configServer;

  @Value("${busrefresh}")
  private String busrefresh;
  // 前置过滤器
  @Override
  public String filterType() {
    return GateWayFilterHandle.FILTERTYPE_PRE;
  }
  // 优先级为0，数字越大，优先级越低
  @Override
  public int filterOrder() {
    return 0;
  }
  // 是否执行该过滤器，此处为true，说明需要过滤
  @Override
  public boolean shouldFilter() {
    //   通过对过滤器过滤规则进行修改，在是否需要过滤方法体中，增加 如果请求类型为OPTIONS ，则不进行用户校验，
    //   直接跳过该过滤，由框架本身去响应该请求。代码如下：

    //      RequestContext ctx = RequestContext.getCurrentContext();
    //      HttpServletRequest request = ctx.getRequest();
    //      if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
    //          return false;
    //      }

    return true;
  }

  int i = 0;

  @Override
  public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();

    HttpServletRequest request = ctx.getRequest();
    //    if(!this.shouldFilter()){
    //      log.debug("*****************FirstFilter run start*****************");
    //      HttpServletResponse response = ctx.getResponse();
    //      response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
    //      response.setHeader("Access-Control-Allow-Credentials","true");
    //      response.setHeader("Access-Control-Allow-Headers","authorization, content-type");
    //      response.setHeader("Access-Control-Allow-Methods","POST,GET");
    //      response.setHeader("Access-Control-Expose-Headers","X-forwared-port, X-forwarded-host");
    //
    // response.setHeader("Vary","Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
    //      //不再路由
    //      ctx.setSendZuulResponse(false);
    //      ctx.setResponseStatusCode(200);
    //      log.debug("*****************FirstFilter run end*****************");
    //    }

    String requestUrl = request.getRequestURL().toString();
    log.info(String.format("%s >>> %s", request.getMethod(), requestUrl));
    try {
      log.info(IpUtil.getIpAddrByNginx(request));
    } catch (UnknownHostException e) {
      e.printStackTrace();
      log.info("ip没有找到UnknownHostException");
    }

    Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
    if (authorization != null) {
      Object obj = authorization.getPrincipal();
      if (obj instanceof UserDetails) {
        UserDetails userDetails = (UserDetails) authorization.getPrincipal();
        log.info(userDetails.toString());
      }
    }

    //    log.debug("zuul " + port + " sessionId:" + ctx.getRequest().getSession().getId());
    log.info("port " + port + "zuul 执行runFilter 次数" + (++i));

    if (requestUrl.contains(authCheckClientMsgUri)) {
      String authorizationStr = clientId + ":" + clientSecret;

      byte[] authorizationBase64 = Base64.encode(authorizationStr.getBytes());

      ctx.addZuulRequestHeader("Authorization", "Basic " + new String(authorizationBase64));
    }
    // 判断前缀是配置中心路由刷新配置接口,清除git发送的body信息解决报错
    if (requestUrl.contains(configServer + busrefresh)) {
      ctx.setRequest(new BusConfigRequestWrapper(request));
      request=ctx.getRequest();
      BufferedReader br = null;
      StringBuilder sb = new StringBuilder();
      String str ="";
      try {
        br = request.getReader();
        while ((str = br.readLine()) != null) {
          sb.append(str);
        }
        br.close();
      } catch (IOException e) {
        e.printStackTrace();
        if (br != null)
          try {
            br.close();
          } catch (IOException eo) {
            eo.printStackTrace();
          }
      } finally {
        if (br != null) {
          try {
            br.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
    }
}





        //
    //    String rpcId = getRPCIDByHeader();
    //    if (rpcId == null) {
    //      rpcId = "" + random.nextInt(100);
    //      setRPCIDToHeader(rpcId);
    //      log.info("zuul生成随机rpcId:" + rpcId);
    //    }
    //    String authorization=ctx.getRequest().getHeader("authorization");
    //    if(authorization!=null){
    //      ctx.addZuulRequestHeader("Authorization", );
    //    }
    HttpSession session = request.getSession(false);
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
      for (Cookie c : cookies) {

        System.out.println(c.getName() + "--->" + c.getValue());
      }

    } else {
      System.out.println("登录校验过滤器AjaxJsonUsernamePasswordAuthenticationFilter获取cookie null");
    }
    Enumeration<String> enumeration = request.getHeaderNames();
    while (enumeration.hasMoreElements()) {
      String name = enumeration.nextElement();
      log.info("header:" + name + " : " + request.getHeader(name));
    }
    if (session != null) {
      System.out.println(
          "SPRING_SECURITY_SAVED_REQUEST:" + session.getAttribute("SPRING_SECURITY_SAVED_REQUEST"));
      System.out.println("网关 获取到的sessionId" + session.getId());

      enumeration = session.getAttributeNames();

      while (enumeration.hasMoreElements()) {
        String name = enumeration.nextElement();
        log.info("sessionAttributeName:" + name + " : " + session.getAttribute(name));
      }
    }

    //    Object accessToken = request.getParameter("token");
    //    if (accessToken == null) {
    //      log.warn("token is empty");
    //      ctx.setSendZuulResponse(false);
    //      ctx.setResponseStatusCode(401);
    //      try {
    //        ctx.getResponse().getWriter().write("token is empty");
    //      } catch (Exception e) {
    //      }
    //
    //      return null;
    //    }
    return null;

  }

  @Override
  public void setRPCIDToHeader(String rpcId) {
    RequestContext.getCurrentContext().addZuulRequestHeader(RPCID, rpcId);
  }

  @Override
  public String getRPCIDByHeader() {
    return RequestContext.getCurrentContext().getRequest().getHeader(RPCID);
  }
}
